package com.hugoo.core.db;

import com.hugoo.core.Conf;
import com.hugoo.core.db.pools.EnvPool;
import com.hugoo.core.db.pools.LxOraclePool;
import com.hugoo.core.db.pools.LxSqlServerPool;
import com.hugoo.core.db.pools.NiCP;
import com.hugoo.core.util.TL;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Hugoo.Chan
 */
public class Conn {

    public enum DB_TYPE {

        ORACLE, SQL_SERVER, MYSQL
    }

    public static DB_TYPE dbt(String dbl) {
        if (TL.isEmpty(dbl) || "-".equals(dbl)) {
            dbl = Conf.getBaseProp("database.type");
        } else {
            dbl = Conf.getBaseProp(dbl, "database.type");
        }
        if ("ORACLE".equalsIgnoreCase(dbl)) {
            return DB_TYPE.ORACLE;
        } else if ("MYSQL".equalsIgnoreCase(dbl)) {
            return DB_TYPE.MYSQL;
        } else if ("SQLSERVER".equalsIgnoreCase(dbl)) {
            return DB_TYPE.SQL_SERVER;
        }
        return DB_TYPE.ORACLE;
    }
    private final static Log log = LogFactory.getLog(Conn.class);

    public static void release(Object... rs) {
        TL.close(rs);
    }
    private static Map<String, NiCP> nicpMgr = new HashMap<String, NiCP>();

    public static Connection conn(String dbl) {
        if (TL.isEmpty(dbl)) {
            dbl = "-";
        }
        NiCP nicp = nicpMgr.get(dbl);
        String inst;
        if (nicp == null) {//如果实例为空,则初始化
            log.info("检测到数据库连接池实例[" + dbl + "]为空,现初始化连接池...");
            if ("-".equals(dbl)) {
                inst = Conf.getBaseProp(Conf._jndi_key);
            } else {
                inst = Conf.getBaseProp(dbl, Conf._jndi_key);
            }
            if (TL.isNotEmpty(inst)) {
                nicp = new EnvPool(inst);
                log.info("连接池实例为" + inst);
            } else {
                if ("-".equals(dbl)) {
                    inst = Conf.getBaseProp("database.inst");
                } else {
                    inst = Conf.getBaseProp(dbl, "database.inst");
                }
                switch (Conn.dbt(dbl)) {
                    case ORACLE:
                        nicp = new LxOraclePool(inst);
                        break;
                    case SQL_SERVER:
                        nicp = new LxSqlServerPool(inst);
                        break;
                    default:
                        log.error("不支持的数据库类型");
                }
                log.info("自定义连接池实例初始化完毕，实例：" + inst);
            }
            if (nicp == null) {
                log.error("无法取到连接实例……");
                return null;
            }
            nicpMgr.put(dbl, nicp);
        }
        return nicp.getConn();
    }
}
